package cn.xo68.boot.auth.server.service;

import java.util.List;

import cn.xo68.boot.auth.core.common.AuthConstants;
import cn.xo68.boot.auth.server.domain.OauthUser;
import cn.xo68.boot.auth.server.domain.OauthUserRole;
import cn.xo68.boot.auth.server.mapper.OauthUserMapper;
import cn.xo68.boot.auth.server.mapper.OauthUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;


/**
 * Oauth2User Service
 * @author wuyy(16349023@qq.com)
 * @date 2018年08月04日 16:22:17
 *
 */
@CacheConfig(cacheNames = {AuthConstants.CACHE_NAME_OAUTH2_USER})
 @Service
public class OauthUserService{

    @Autowired
    private OauthUserMapper oauthUserMapper;

    @Autowired
    private OauthUserRoleMapper oauthUserRoleMapper;

    @Cacheable(key = "#userId")
    public OauthUser getByUserId(String userId) {
        return  oauthUserMapper.getByUserId(userId);
    }

    @Cacheable(key = "#account")
    public OauthUser getByAccount(String account) {
        return  oauthUserMapper.getByAccount(account);
    }

    @Caching(evict = {@CacheEvict(key = "#oauthUser.userId"),
            @CacheEvict(key = "#oauthUser.account")})
    @Transactional(rollbackFor = Exception.class)
    public void insert(OauthUser oauthUser, List<OauthUserRole> roles) {
        oauthUserMapper.insert(oauthUser);
        oauthUserRoleMapper.delete(oauthUser.getUserId());
        for (OauthUserRole role: roles) {
            oauthUserRoleMapper.insert(role);
        }
    }
    @Caching(evict = {@CacheEvict(key = "#oauthUser.userId"),
            @CacheEvict(key = "#oauthUser.account")})
    public void update(OauthUser oauthUser, List<OauthUserRole> roles) {
        oauthUserMapper.update(oauthUser);
        oauthUserRoleMapper.delete(oauthUser.getUserId());
        for (OauthUserRole role: roles) {
            oauthUserRoleMapper.insert(role);
        }
    }

    @Caching(evict = {@CacheEvict(key = "#userId")})
    public void delete(String userId) {
        oauthUserMapper.delete(userId);
    }
    
    public List<OauthUser> list() {
        return oauthUserMapper.list();
    }
	
	public PageInfo<OauthUser> list(int pageNumber, int pageSize) {
        PageHelper.startPage(pageNumber, pageSize,true);
        List<OauthUser> docs = oauthUserMapper.list();
        PageInfo<OauthUser> pageInfo = new PageInfo<>(docs);
        return pageInfo;
    }
}